#pragma once
#include <iostream>
#include "Protocol.hpp"

class Calculator
{
public:
    Calculator()
    {
    }
    Response Execute(const Request &req)
    {
        Response resp;
        switch (req.Oper())
        {
        case '+':
            resp.SetResult(req.X() + req.Y());
            break;
        case '-':
            resp.SetResult(req.X() - req.Y());
            break;
        case '*':
            resp.SetResult(req.X() * req.Y());
            break;
        case '/':
        {
            if (req.Y() == 0)
            {
                resp.SetCode(1); // 除0 错误码设为1
            }
            else
            {
                resp.SetResult(req.X() / req.Y());
            }
        }
        break;
        case '%':
        {
            if (req.Y() == 0)
            {
                resp.SetCode(2); // 模0 错误码设为2
            }
            else
            {
                resp.SetResult(req.X() % req.Y());
            }
        }
        break;
        default:
            resp.SetCode(3); // 用户发来的计算类型无法识别 错误码设为3
            break;
        }
        return resp;
    }
    ~Calculator()
    {
    }
private:
}cal;

std::string HandlerRequest(std::string &inbuffer)
{
    std::string request_str;
    std::string result_str; 
    while(Decode(inbuffer, &request_str))
    {
        std::string resp_str;
        // 一定拿到一个完整的报文
        // 1. 反序列化报文
        if(request_str.empty())
            break;
        Request req;
        if(!req.Deserialization(request_str))
            break;
        std::cout<<"##################"<<std::endl;
        std::cout<<"x: "<<req.X()<<" y: "<<req.Y()<<" oper: "<<req.Oper()<<std::endl;
        std::cout<<"##################"<<std::endl;

        // 2.业务处理
        Response res = cal.Execute(req);

        // 3.序列化响应报文
        res.Serialization(resp_str);

        // 4.添加长度说明
        Encode(resp_str); 
        
        // 5.添加所有应答
        result_str += resp_str;

    }
    return result_str;
}